package org.sdnstproject.interlayer.interlayerProxy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StrategesGen {
	private static final Logger log = LoggerFactory.getLogger(StrategesGen.class);
	
	public static void printToFile(ArrayList<String> stra, String file) {
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			fileWriter = new FileWriter(file);
			bufferedWriter =new BufferedWriter(fileWriter);
			for(String s:stra) {
				bufferedWriter.write(s);
				bufferedWriter.write('\n');
				bufferedWriter.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bufferedWriter != null) {
				try {
					bufferedWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static ArrayList<String> readFromFile(String file) {
		ArrayList<String> stra = new ArrayList<String>();
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			fileReader = new FileReader(file);
			bufferedReader =new BufferedReader(fileReader);
			String line = null;
			while((line = bufferedReader.readLine()) != null) {
				stra.add(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return stra;
	}
	
//"ofVersion:"+ofVersion+",ofType:"+ofType+",childType:"+childType+",testWhich:"+testWhich+",action:"+action+",field:"+field+",actionValue:"+actionValue;
	public static Strategy getStrategyObject(String stra) {
		String[] stras = stra.split(",");
		if(stras.length != 6) {
			log.info("please check the strategy!");
			return null;
		}
		String ofVersion = null;
		String ofType = null;
		String childType = null;
		String testWhich = null;
		String action = null;
		String field = null;
		String actionValue = null;
		for(String ss:stras) {
			String[] st = ss.split(":");
			if(st.length != 2) {
				log.info("please check the strategy!");
				return null;
			}
			switch (st[0]) {
			case "ofVersion":
				ofVersion = st[1];
				break;
			case "ofType":
				ofType = st[1];
				break;
			case "childType":
				childType = st[1];
				break;
			case "testWhich":
				testWhich = st[1];
				break;
			case "action":
				action = st[1];
				break;
			case "field":
				field = st[1];
				break;
			case "actionValue":
				actionValue = st[1];
				break;
			}
		}
		return new Strategy(ofVersion, ofType, childType, testWhich, action, field, actionValue);
	}
}
